<template>
    <base-modal
        :title="pageType === 'edit' ? '危大工程管控计划项编辑' : '危大工程管控计划项添加'"
        cancelText="取消"
        okText="保存"
        :width="800"
        v-on="$listeners"
        @ok="handleSave"
        :confirm-loading="loading.isSaving"
    >
        <a-form-model ref="form" :model="formInfo" :rules="rules" :hideRequiredMark="true">
            <a-row :gutter="24">
                <a-col :md="12" :sm="12">
                    <a-form-model-item
                        label="分类"
                        :labelCol="{ lg: { span: 6 }, sm: { span: 5 } }"
                        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                        prop="projectType"
                    >
                        <a-select placeholder="请选择" v-model="formInfo.projectType">
                            <a-select-option v-for="item in enabledTypeList" :key="item.id" :value="item.id">{{
                                item.name
                            }}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col>
                <a-col :md="12" :sm="12">
                    <a-form-model-item
                        label="级别"
                        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                        prop="projectLevel"
                    >
                        <a-select placeholder="请选择" v-model="formInfo.projectLevel">
                            <a-select-option v-for="item in levelList" :key="item.id" :value="item.id">{{
                                item.name
                            }}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :md="12" :sm="12">
                    <a-form-model-item
                        label="责任部门\人"
                        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                        prop="respEmployeeId"
                    >
                        <SelectPersonByProject
                            placeholder="请选择"
                            :projectId="initData.projectId"
                            :currentLabel.sync="labelInfo.respEmployeeName"
                            v-model="formInfo.respEmployeeId"
                        />
                    </a-form-model-item>
                </a-col>
                <a-col :md="12" :sm="12">
                    <a-form-model-item
                        label="施工部位"
                        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                        prop="constructionSiteIds"
                    >
                        <a-tree-select
                            placeholder="请选择或输入"
                            v-model="formInfo.constructionSiteIds"
                            :searchValue.sync="formInfo.constructionSiteDesc"
                            style="width: 100%"
                            :tree-data="treeData"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :replaceFields="treeReplace"
                            multiple
                        />
                    </a-form-model-item>
                </a-col>
            </a-row>
            <!-- <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            label="施工部位"
            :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
            :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
            help="选择或输入施工部位信息"
          >
            <a-col :span="24">
              <BaseTextarea
                :disabled="formInfo.constructionSiteIds.length > 0"
                style="resize: none"
                placeholder="请输入"
                v-model="formInfo.constructionSiteDesc"
                :rows="2"
              />
            </a-col>
          </a-form-model-item>
        </a-col>
      </a-row> -->
            <a-row :gutter="24">
                <a-col :span="24">
                    <a-form-model-item
                        label="危大工程具体情况"
                        :labelCol="{ lg: { span: 3 }, sm: { span: 3 } }"
                        :wrapperCol="{ lg: { span: 21 }, sm: { span: 21 } }"
                        prop="detailInfo"
                    >
                        <a-col :span="24">
                            <BaseTextarea
                                style="resize: none"
                                placeholder="请输入"
                                v-model="formInfo.detailInfo"
                                :rows="2"
                            />
                        </a-col>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :span="24">
                    <a-form-model-item
                        label="可能导致的事故"
                        :labelCol="{ lg: { span: 3 }, sm: { span: 3 } }"
                        :wrapperCol="{ lg: { span: 21 }, sm: { span: 21 } }"
                        prop="possibleAccidents"
                    >
                        <a-col :span="24">
                            <BaseTextarea
                                style="resize: none"
                                placeholder="请输入"
                                v-model="formInfo.possibleAccidents"
                                :rows="2"
                            />
                        </a-col>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :span="24">
                    <a-form-model-item
                        label="计划控制措施"
                        :labelCol="{ lg: { span: 3 }, sm: { span: 3 } }"
                        :wrapperCol="{ lg: { span: 21 }, sm: { span: 21 } }"
                        prop="controlMeasures"
                        help="具有操作性"
                    >
                        <a-col :span="24">
                            <BaseTextarea
                                style="resize: none"
                                placeholder="请输入"
                                v-model="formInfo.controlMeasures"
                                :rows="2"
                            />
                        </a-col>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :md="12" :sm="12">
                    <a-form-model-item
                        label="开始时间"
                        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                        prop="startDate"
                    >
                        <a-date-picker v-model="formInfo.startDate" />
                    </a-form-model-item>
                </a-col>
                <a-col :md="12" :sm="12">
                    <a-form-model-item
                        label="结束时间"
                        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                        prop="endDate"
                    >
                        <a-date-picker v-model="formInfo.endDate" />
                    </a-form-model-item>
                </a-col>
            </a-row>
        </a-form-model>
    </base-modal>
</template>

<script>
import SelectPersonByProject from '@/components/Select/SelectPersonByProject.vue'
import { getSelectListByType } from '@/api/safetySupervision/common.js'
import { selectOption } from '@/api/material/goods/goods'
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import BaseModal from '@/components/BaseModal'
import Moment from 'moment'
import { getWBS } from '@/api/safetySupervision/safteyClosureRecord'

export default {
    name:'a'+Date.now(),    components: {
        BaseModal,
        TreeSelectOrganization,
        SelectPersonByProject,
    },
    props: {
        initData: {
            type: Object,
            default() {
                return {}
            },
        },
    },
    data() {
        const validateStart = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请选择开始时间'))
            } else {
                if (value.isBefore && value.isBefore(this.formInfo.endDate)) {
                    this.$refs.form.validateField('endDate')
                } else if (this.formInfo.endDate) {
                    callback(new Error('开始时间需小于结束时间'))
                }
                callback()
            }
        }
        const validateEnd = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请选择结束时间'))
            } else {
                if (value.isAfter && value.isAfter(this.formInfo.startDate)) {
                    this.$refs.form.validateField('startDate')
                } else if (this.formInfo.startDate) {
                    callback(new Error('结束时间需大于开始时间'))
                }
                callback()
            }
        }
        return {
            oldConstructionSiteDesc: '', // 存储
            treeReplace: {
                title: 'label',
                value: 'id',
                key: 'id',
            },
            treeData: [],
            labelInfo: {
                respEmployeeName: '',
            },
            levelList: [], // 级别列表
            typeList: [], // 分类列表
            partArr: [], // 施工部位列表
            loading: {
                isSaving: false,
            },
            treeExpandedKeys: [],
            value: undefined,
            pageType: 'add',
            formInfo: {
                projectType: '',
                projectLevel: '',
                respEmployeeId: '',
                detailInfo: '',
                possibleAccidents: '',
                constructionSiteIds: [],
                constructionSiteDesc: '',
                situation: '',
                controlMeasures: '',
                startDate: '',
                endDate: '',
            },
            rules: {
                projectType: [{ required: true, message: '请选择', trigger: 'change' }],
                projectLevel: [{ required: true, message: '请选择', trigger: 'change' }],
                respEmployeeId: [{ required: true, message: '请选择', trigger: 'change' }],
                detailInfo: [{ required: true, message: '请输入', trigger: 'change' }],
                possibleAccidents: [{ required: true, message: '请输入', trigger: 'change' }],
                situation: [{ required: true, message: '请输入', trigger: 'change' }],
                controlMeasures: [{ required: true, message: '请输入', trigger: 'change' }],
                startDate: [{ validator: validateStart, trigger: 'change' }],
                endDate: [{ validator: validateEnd, trigger: 'change' }],
            },
        }
    },
    computed: {
        enabledTypeList() {
            return this.typeList.filter((item) => !!item.enabled)
        },
    },
    created() {
        this.initPage()
        this.getAllSelectList()
        this.getPart()
        this.getWBS()
    },
    methods: {
        // 获取模板
        getWBS() {
            if (!this.initData.projectId) return
            let params = {
                projectId: this.initData.projectId,
            }
            getWBS(params).then((res) => {
                if (res.code === 200) {
                    this.treeData = res.data.list
                    if (this.oldConstructionSiteDesc) {
                        const descList = this.oldConstructionSiteDesc.split('、')
                        const getLabel = (list) => {
                            // 筛选掉treeData中已有的值，区分是填写的值还是选择的值
                            list.forEach((item) => {
                                const index = descList.findIndex((descItem) => descItem === item.label)
                                if (index > -1) {
                                    descList.splice(index, 1)
                                }
                                if (item.children && item.children.length > 0) {
                                    getLabel(item.children)
                                }
                            })
                        }
                        getLabel(this.treeData)
                        this.formInfo.constructionSiteDesc = descList.join('、')
                    }
                }
            })
        },
        initPage() {
            const { projectType, projectLevel, respEmployeeName, constructionSiteIds, respEmployeeId } = this.initData
            this.formInfo = {
                ...this.formInfo,
                ...this.initData,
                startDate: Moment(this.initData.startDate),
                endDate: Moment(this.initData.endDate),
                projectType: projectType?.id,

                projectLevel: projectLevel?.id,
            }
            console.log(this.initData.respEmployeeId)
            this.$nextTick(() => {
                this.formInfo.respEmployeeId = this.initData.respEmployeeId
                console.log(this.formInfo)
            })

            if (Array.isArray(respEmployeeName)) {
                // 避免责任部门/责任人 label值的丢失
                this.labelInfo.respEmployeeName = respEmployeeName.length > 0 ? respEmployeeName[0] : ''
            } else {
                this.labelInfo.respEmployeeName = respEmployeeName
            }
            // 存下constructionSiteDesc的旧值，待获取到treeData数据后，再用来筛选
            this.oldConstructionSiteDesc = this.formInfo.constructionSiteDesc
            this.formInfo.constructionSiteDesc = ''
        },

        // 获取下拉列表数据
        getAllSelectList() {
            const loopList = [
                {
                    name: 'typeList',
                    type: 8,
                },
                {
                    name: 'levelList',
                    type: 0,
                },
            ]
            loopList.forEach((item) => {
                this.getSelectList(item.type, item.name)
            })
        },
        async getSelectList(type, name) {
            const [err, res] = await getSelectListByType({ type })
            if (!err) {
                this[name] = res.data || []
            }
        },
        // 获取施工部位列表
        getPart() {
            let _this = this
            selectOption({
                type: 3,
            }).then((res) => {
                if (res.code === 200) {
                    _this.partArr = res.data
                }
            })
        },
        handleSave() {
            this.$refs.form.validate((valid) => {
                if (!valid) return
                if (this.loading.isSaving) return
                this.loading.isSaving = true
                const { startDate, endDate, constructionSiteDesc, constructionSiteIds } = this.formInfo
                let desc = ''
                if (constructionSiteIds.length > 0) {
                    const getLabel = (list) => {
                        // 获取施工部位的label值
                        list.forEach((item) => {
                            if (constructionSiteIds.includes(item.id)) {
                                desc += '、' + item.label
                            }
                            if (item.children && item.children.length > 0) {
                                getLabel(item.children)
                            }
                        })
                    }
                    getLabel(this.treeData)
                    desc = desc.substring(1)
                    if (constructionSiteDesc) {
                        desc += '、' + constructionSiteDesc
                    }
                } else {
                    desc = constructionSiteDesc
                }
                let data = this.$clone(this.formInfo)
                console.log(data)
                let projectType = this.enabledTypeList.filter((item) => item.id == data.projectType)[0]
                let projectLevel = this.levelList.filter((item) => item.id == data.projectLevel)[0]
                //  let respEmployeeName = this.labelInfo.respEmployeeName
                this.$emit('confirm', {
                    ...data,
                    startDate: startDate.format('YYYY-MM-DD'),
                    endDate: endDate.format('YYYY-MM-DD'),
                    projectType: projectType,
                    projectLevel: projectLevel,
                    constructionSiteDesc: desc,
                    respEmployeeName:this.labelInfo.respEmployeeName
                })
                this.loading.isSaving = false
            })
        },
    },
}
</script>

<style lang="less" scoped>
form .ant-mentions,
form textarea.ant-input {
    height: auto !important;
    width: 100%;
}
</style>
